package io.webfolder.cdp.pdf;

import static java.awt.Desktop.getDesktop;
import static java.awt.Desktop.isDesktopSupported;
import static java.nio.file.Files.write;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import io.webfolder.cdp.Launcher;
import io.webfolder.cdp.Options;
import io.webfolder.cdp.session.Session;
import io.webfolder.cdp.session.SessionFactory;

public class PrintToPDF {

	public static void html2PDF() throws IOException {

		Path file = Paths.get(".", "cdp4j.pdf");

		Options options = Options.builder().headless(true).build();

		Launcher launcher = new Launcher(options);

		try (SessionFactory factory = launcher.launch()) {

			String context = factory.createBrowserContext();
			try (Session session = factory.create(context)) {

				session.navigate("https://www.baidu.com");
				session.waitDocumentReady();

				byte[] content = session.printToPDF();
				write(file, content);
			}

			factory.disposeBrowserContext(context);
		}

		if (isDesktopSupported()) {
			getDesktop().open(file.toFile());
		}

		launcher.kill();
	}

	public static void main(String[] args) throws IOException {

		html2PDF();

	}
}
